package com.zt.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zt.reggie.common.BaseContext;
import com.zt.reggie.common.Constant;
import com.zt.reggie.common.R;
import com.zt.reggie.entity.User;
import com.zt.reggie.service.UserService;
import com.zt.reggie.utils.SMSUtils;
import com.zt.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec com.zt.reggie.controller
 * @since 2023 - 02 - 27 - 20:35
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();

        if(StringUtils.isNotEmpty(phone)){
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码：{}", code);
            //发送短信
//            SMSUtils.sendMessage("", "", phone, code);
            //将生成的验证码保存到session
//            session.setAttribute(phone, code);

            //将生成的验证码缓存到 Redis
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

            return R.success("发送成功!");
        }

        return R.error("发送失败!");
    }


    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> userInfo, HttpSession session){
        log.info("用户登录:{}", userInfo.toString());
        //获取手机号
        String phone = userInfo.get("phone");
        //获取验证码
        String code = userInfo.get("code");

        //从Session中取出验证码
//        String sessionCode = (String)session.getAttribute(Constant.SESSION_CODE);
        String redisCode = (String)redisTemplate.opsForValue().get(phone);
        //验证码比对
        if(redisCode != null && redisCode.equals(code)){
            //判断用户是否存在
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User user = userService.getOne(wrapper);
            if(user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute(Constant.SESSION_USER, user.getId());
            //登录成功，从Redis中删除验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }

        return R.error("登录失败");
    }
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute(Constant.SESSION_USER);
        return R.success("退出成功");
    }
}
